﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using System.Collections;
using System.ComponentModel;

namespace LibraryUtility.Common
{
    /// <summary>
    /// ClassName:UpLoadPic
    /// Auther:Leo.wl
    /// Time:2010-04-15
    /// </summary>
    public class UpLoadPic
    {
        #region   图片上传

        #region 图片上传类【一】
        ///<summary>
        /// 图片上传类【一】
        /// 生成缩略图
        /// </summary>
        /// <param name="MyFile">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public string MakeThumbnail(HttpPostedFile MyFile, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = Image.FromStream(MyFile.InputStream);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            //hyey.wl mod 09.12.07 :create file directory.
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(thumbnailPath)))
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(thumbnailPath));

            string strGuid = System.Guid.NewGuid().ToString().ToUpper();
            thumbnailPath += strGuid + ".jpg";

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(HttpContext.Current.Server.MapPath(thumbnailPath), System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
            return thumbnailPath;
        }

        #endregion

        #region 图片上传类【二】
        /// <summary>
        /// 图片上传类【二】
        /// asp.net上传图片并生成缩略图
        /// </summary>
        /// <param name="upImage">HtmlInputFile控件</param>
        /// <param name="sSavePath">保存的路径,些为相对服务器路径的下的文件夹</param>
        /// <param name="sThumbExtension">缩略图的thumb</param>
        /// <param name="intThumbWidth">生成缩略图的宽度</param>
        /// <param name="intThumbHeight">生成缩略图的高度</param>
        /// <returns>缩略图名称</returns>
        public string UpLoadImage(HtmlInputFile upImage, string sSavePath, string sThumbExtension, int intThumbWidth, int intThumbHeight)
        {

            string sThumbFile = "";

            string sFilename = "";



            if (upImage.PostedFile != null)
            {

                HttpPostedFile myFile = upImage.PostedFile;

                int nFileLen = myFile.ContentLength;

                if (nFileLen == 0)

                    return "没有选择上传图片";



                //获取upImage选择文件的扩展名

                string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower();

                //判断是否为图片格式

                if (extendName != ".jpg" && extendName != ".jpge" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png")

                    return "图片格式不正确";





                byte[] myData = new Byte[nFileLen];

                myFile.InputStream.Read(myData, 0, nFileLen);



                sFilename = System.IO.Path.GetFileName(myFile.FileName);

                int file_append = 0;

                //检查当前文件夹下是否有同名图片,有则在文件名+1

                while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))
                {

                    file_append++;

                    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)

                        + file_append.ToString() + extendName;

                }

                System.IO.FileStream newFile

                    = new System.IO.FileStream(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename),

                    System.IO.FileMode.Create, System.IO.FileAccess.Write);

                newFile.Write(myData, 0, myData.Length);

                newFile.Close();



                //以上为上传原图



                try
                {

                    //原图加载

                    using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))
                    {

                        //原图宽度和高度

                        int width = sourceImage.Width;

                        int height = sourceImage.Height;

                        int smallWidth;

                        int smallHeight;



                        //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽  和 原图的高/缩略图的高)

                        if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
                        {

                            smallWidth = intThumbWidth;

                            smallHeight = intThumbWidth * height / width;

                        }

                        else
                        {

                            smallWidth = intThumbHeight * width / height;

                            smallHeight = intThumbHeight;

                        }



                        //判断缩略图在当前文件夹下是否同名称文件存在

                        file_append = 0;

                        sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + extendName;



                        while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sThumbFile)))
                        {

                            file_append++;

                            sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +

                                file_append.ToString() + extendName;

                        }

                        //缩略图保存的绝对路径

                        string smallImagePath = System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile;



                        //新建一个图板,以最小等比例压缩大小绘制原图

                        using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
                        {

                            //绘制中间图

                            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                            {

                                //高清,平滑

                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                                g.Clear(Color.Black);

                                g.DrawImage(

                                    sourceImage,

                                    new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),

                                    new System.Drawing.Rectangle(0, 0, width, height),

                                    System.Drawing.GraphicsUnit.Pixel

                                    );

                            }

                            //新建一个图板,以缩略图大小绘制中间图

                            using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                            {

                                //绘制缩略图

                                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                                {

                                    //高清,平滑

                                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                                    g.Clear(Color.Black);

                                    int lwidth = (smallWidth - intThumbWidth) / 2;

                                    int bheight = (smallHeight - intThumbHeight) / 2;

                                    g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);

                                    g.Dispose();


                                    //hyey.wl mod 09.12.07
                                    string dirpath = HttpContext.Current.Server.MapPath(sSavePath);
                                    if (!Directory.Exists(dirpath))
                                        Directory.CreateDirectory(dirpath);

                                    bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                                }

                            }

                        }

                    }

                }

                catch
                {

                    //出错则删除

                    System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename));

                    return "图片格式不正确";

                }

                //返回缩略图名称

                return sThumbFile;

            }

            return "没有选择图片";

        }
        #endregion

        #region 图片上传类【三】

        /// <summary>
        /// Ups the load.
        /// bug:页面错误
        /// </summary>
        /// <param name="MyPostedFile">My posted file.</param>
        /// <param name="height">The height.</param>
        /// <param name="width">The width.</param>
        /// <param name="savePath">The save path.</param>
        /// <returns></returns>
        public string UpLoad(HttpPostedFile MyPostedFile, int height, int width, string savePath)
        {

            if (MyPostedFile.ContentType.ToString().ToLower().IndexOf("image") < 0)
            {
                HttpContext.Current.Response.Write("<script>alert('无效的图形格式');</script>");
                return "0";
            }
            string url = GetThumbNail(MyPostedFile.FileName, height, width, MyPostedFile.ContentType.ToString(), false, MyPostedFile.InputStream, savePath);
            return url;
        }

        /// <summary>
        /// Gets the thumb nail.
        /// </summary>
        /// <param name="strFileName">Name of the STR file.</param>
        /// <param name="iWidth">Width of the i.</param>
        /// <param name="iheight">The iheight.</param>
        /// <param name="strContentType">Type of the STR content.</param>
        /// <param name="blnGetFromFile">if set to <c>true</c> [BLN get from file].</param>
        /// <param name="ImgStream">The img stream.</param>
        /// <param name="savePath">The save path.</param>
        /// <returns></returns>
        private string GetThumbNail(string strFileName, int iWidth, int iheight, string strContentType, bool blnGetFromFile, System.IO.Stream ImgStream, string savePath)
        {
            System.Drawing.Image oImg;
            if (blnGetFromFile)
            {
                oImg = System.Drawing.Image.FromFile(strFileName);
            }
            else
            {
                oImg = System.Drawing.Image.FromStream(ImgStream);
            }
            oImg = oImg.GetThumbnailImage(iWidth, iheight, null, IntPtr.Zero);
            string strGuid = System.Guid.NewGuid().ToString().ToUpper();
            string strFileExt = strFileName.Substring(strFileName.LastIndexOf(".")).ToLower();
            HttpContext.Current.Response.ContentType = strContentType;
            string HardWarePath = HttpContext.Current.Server.MapPath(savePath) + strGuid + strFileExt;

            //hyey.wl mod 09.12.07
            string dirpath = HttpContext.Current.Server.MapPath(savePath);
            if (!Directory.Exists(dirpath))
                Directory.CreateDirectory(dirpath);


            try
            {
                oImg.Save(HardWarePath, GetImageType(strContentType));
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                oImg.Dispose();
            }
            return savePath + strGuid + strFileExt;
        }

        private System.Drawing.Imaging.ImageFormat GetImageType(object strContentType)
        {
            if ((strContentType.ToString().ToLower()) == "image/pjpeg")
            {
                return System.Drawing.Imaging.ImageFormat.Jpeg;
            }
            else if ((strContentType.ToString().ToLower()) == "image/gif")
            {
                return System.Drawing.Imaging.ImageFormat.Gif;
            }
            else if ((strContentType.ToString().ToLower()) == "image/bmp")
            {
                return System.Drawing.Imaging.ImageFormat.Bmp;
            }
            else if ((strContentType.ToString().ToLower()) == "image/tiff")
            {
                return System.Drawing.Imaging.ImageFormat.Tiff;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-icon")
            {
                return System.Drawing.Imaging.ImageFormat.Icon;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-png")
            {
                return System.Drawing.Imaging.ImageFormat.Png;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-emf")
            {
                return System.Drawing.Imaging.ImageFormat.Emf;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-exif")
            {
                return System.Drawing.Imaging.ImageFormat.Exif;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-wmf")
            {
                return System.Drawing.Imaging.ImageFormat.Wmf;
            }
            else
            {
                return System.Drawing.Imaging.ImageFormat.MemoryBmp;
            }
        }
        #endregion

        #endregion
    }
}
